package com.frejoys.api.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.frejoys.api.interfaces.ApiCommonInterface;
import com.frejoys.api.service.ApiAppService;
import com.frejoys.common.constant.CommonConstant;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.vo.common.PushVo;
import com.frejoys.common.vo.common.WxH5UserInfoVo;
import com.frejoys.common.vo.common.WxH5Vo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

// 获取收费气象数据
@Slf4j
@Service
@RequiredArgsConstructor
public class ApiAppServiceImpl implements ApiAppService {

    private final ApiCommonInterface apiCommonInterface;

    @Override
    public byte[] getWxQrcodeByte(String accessToken, String scene, Integer width) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("scene", scene);
            map.put("width", width);
            Mono<byte[]> mono = apiCommonInterface.getWxQrCodeUrlApiInfo(accessToken, map);
            return mono.block();
        } catch (Exception e) {
            // e.printStackTrace();
            log.error("微信小程序码异常：", e);
        }

        return null;
    }

    /**
     * 获取H5微信access_token
     *
     * @param appid
     * @param secret
     * @param code
     */
    @Override
    public WxH5Vo getH5WxAccessToken(String appid, String secret, String code) {

        WxH5Vo vo = null;
        try {
            Mono<String> mono = apiCommonInterface.getWxAccessTokenApiInfo(appid, secret, code);
            String block = mono.block();

            if (StrUtil.isNotEmpty(block)) {
                vo = new WxH5Vo();
                JSONObject object = JSONUtil.parseObj(block);
                if (CommonConstant.errCode.equals(object.get(CommonConstant.errcodeString))) {
                    throw new GeneralException(HttpStatus.invalidCode);
                }

                if (!CommonConstant.successCode.equals(object.get(CommonConstant.errcodeString))) {
                    throw new GeneralException(HttpStatus.wxLoginError);
                }

                Object accessToken = object.get("access_token");
                Object refreshToken = object.get("refresh_token");
                Object openid = object.get("openid");
                vo.setAccessToken((String) accessToken);
                vo.setRefreshToken((String) refreshToken);
                vo.setOpenId((String) openid);
            }
        } catch (Exception e) {
            log.error("微信H5access_token异常：", e);
            throw new GeneralException(HttpStatus.systemError);
        }
        return vo;
    }

    /**
     * 验证accessToken是否有效
     *
     * @param accessToken
     * @param openid
     */
    @Override
    public boolean validateAccessToken(String accessToken, String openid) {
        try {
            Mono<String> mono = apiCommonInterface.validateAccessTokenApiInfo(accessToken, openid);
            String block = mono.block();

            if (StrUtil.isNotEmpty(block)) {
                JSONObject object = JSONUtil.parseObj(block);
                return CommonConstant.successCode.equals(object.get(CommonConstant.errcodeString));
            }
        } catch (Exception e) {
            log.error("微信验证access_token异常：", e);
            throw new GeneralException(HttpStatus.systemError);
        }
        return false;
    }

    /**
     * 刷新H5 access_token
     *
     * @param appid
     * @param refreshToken
     */
    @Override
    public WxH5Vo h5WxRefreshToken(String appid, String refreshToken) {

        WxH5Vo vo = null;
        try {
            Mono<String> mono = apiCommonInterface.wxRefreshTokenApiInfo(appid, refreshToken);
            String block = mono.block();
            if (StrUtil.isNotEmpty(block)) {
                vo = new WxH5Vo();
                JSONObject object = JSONUtil.parseObj(block);
                if (CommonConstant.refreshTokenErrCode.equals(object.get(CommonConstant.errcodeString))) {
                    throw new GeneralException(HttpStatus.invalidCode);
                }

                Object accessToken = object.get("access_token");
                Object newRefreshToken = object.get("refresh_token");
                Object openid = object.get("openid");
                vo.setAccessToken((String) accessToken);
                vo.setRefreshToken((String) newRefreshToken);
                vo.setOpenId((String) openid);
            }
        } catch (Exception e) {
            log.error("微信刷新access_token异常：", e);
            throw new GeneralException(HttpStatus.systemError);
        }
        return vo;
    }

    @Override
    public WxH5UserInfoVo h5GetUserInfo(String accessToken, String openid) {

        WxH5UserInfoVo vo = null;

        try {
            Mono<String> mono = apiCommonInterface.getUserinfo(accessToken, openid);
            String block = mono.block();

            if (StrUtil.isNotEmpty(block)) {
                vo = new WxH5UserInfoVo();
                JSONObject object = JSONUtil.parseObj(block);
                if (!CommonConstant.successCode.equals(object.get(CommonConstant.errcodeString))) {
                    throw new GeneralException(HttpStatus.wxLoginError);
                }

                Object nickname = object.get("nickname");
                Object unionid = object.get("unionid");
                vo.setUnionid((String) unionid);
                vo.setOpenid(openid);
                vo.setNickname((String) nickname);
//                vo.setSex();
//                vo.setHeadimgurl();
            }
        } catch (Exception e) {
            log.error("获取微信access_token异常：", e);
            throw new GeneralException(HttpStatus.systemError);
        }
        return vo;
    }

    // private final ValueConfig valueConfig;
    //
    // private final ApiWeatherInterface apiWeatherInterface;
    //
    // public WeatherChargeApiVo weatherInfo(Double lng, Double lat) {
    //     WeatherChargeApiVo vo = null;
    //
    //     Mono<String> mono = apiWeatherInterface.getWeatherChargeApiInfo(3, lng, lat, 1, "APPCODE " + valueConfig.getWeatherChargeAppCode());
    //
    //     String result = mono.block();
    //
    //     if (!StrUtil.isEmpty(result)) {
    //         vo = JSONUtil.toBean(result, WeatherChargeApiVo.class);
    //     }
    //
    //     return vo;
    // }

//    private final ApiCommonInterface apiCommonInterface;
//
//    @Override
//    public void wxQrCodeUrlApiInfo() {
//        Mono<String> aa = apiCommonInterface.getWxQrCodeUrlApiInfo("sadfasfasdfa",112l);
//        System.out.println(aa.block());
//
//    }


    @Override
    public void pushVoice(PushVo pushVo) {
        try {
            Mono<String> mono = apiCommonInterface.pushVoice(pushVo);
            mono.block();
        } catch (Exception e) {
            log.error("语音推送接口：", e);
        }
    }
}
